package com.example.flower_shop.service.usr.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.flower_shop.common.PageResult;
import com.example.flower_shop.entity.StoreProduct;
import com.example.flower_shop.exception.exception;
import com.example.flower_shop.mapper.StoreProductMapper;
import com.example.flower_shop.service.usr.UserCollectService;
import com.example.flower_shop.service.usr.UsrProductService;
import com.example.flower_shop.utils.DecimalUtil;
import com.example.flower_shop.vo.product.UniPageVO;
import com.example.flower_shop.vo.product.UsrProductDetail;
import com.example.flower_shop.vo.product.UsrProductPageReq;
import com.example.flower_shop.vo.product.UsrProductPageResp;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class UsrProductServiceImpl implements UsrProductService {

    @Resource
    private StoreProductMapper productMapper;
    @Resource
    private UserCollectService collectService;

    @Override
    public UsrProductDetail findById(Long productId) {
        StoreProduct product = productMapper.selectById(productId);
        if (product == null) {
            throw new exception("商品不存在");
        }
        UsrProductDetail detail = BeanUtil.toBean(product, UsrProductDetail.class);
        // 获取当前用户是否收藏了该商品
        detail.setIsCollect(collectService.hasCollected(productId));
        detail.setVipPrice(DecimalUtil.vip(product.getPrice()));
        return detail;
    }

    @Override
    public PageResult<UsrProductPageResp> productPage(UsrProductPageReq req) {
        Page<UsrProductPageResp> page = new Page<>(req.getPage(), req.getSize());
        UniPageVO uniPageVO = BeanUtil.copyProperties(req, UniPageVO.class);
        IPage<UsrProductPageResp> iPage = productMapper.usrProductPage(page, uniPageVO);
        return PageResult.of(iPage.getTotal(), iPage.getCurrent(),
                iPage.getSize(), setVipPrice(iPage.getRecords()));
    }

    @Override
    public List<UsrProductPageResp> guessYouLike() {
        return setVipPrice(productMapper.guessYouLike());
    }

    private List<UsrProductPageResp> setVipPrice(List<UsrProductPageResp> list) {
        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }
        return list.stream().peek(
                e -> e.setVipPrice(DecimalUtil.vip(e.getPrice()))
        ).toList();
    }

}
